#code=utf-8
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import webapp, db
from model.user import User
from lib import util
from model.stream import Stream
from model.subscription import Subscription
from model.batch_log import BatchLog
import logging
import simplejson


class MainHandler(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        self.response.out.write('hello word')


class InitHandler(webapp.RequestHandler):

    def get(self, method):
        msg = 'hello'
        if method == 'add':
            msg = 'add user ok'
            try:
                User.get_or_insert(key_name='1386', user_id=1386, name='user1', geo=db.GeoPt(36.6, 108.6))
                User.get_or_insert(key_name='1387', user_id=1387, name='user2', geo=db.GeoPt(36.8, 108.8))
            except:
                msg = util.trace()
        elif method == 'clear':
            logging.info('clear')
            kind = self.request.get('kind', 'sub')
            limit = int(self.request.get('limit', 1000))
            msg = 'clear ok'
            if kind == 'all':
                try:
                    users = User.all().fetch(limit)
                    db.delete_async(users)
                    streams = Stream.all().fetch(limit)
                    db.delete_async(streams)
                    subscriptions = Subscription.all().fetch(limit)
                    db.delete_async(subscriptions)
                    batchLogs = BatchLog.all().fetch(limit)
                    db.delete_async(batchLogs)
                    msg += 'delete user:%d, stream:%d, subscription:%d, batch log:%d' % (len(users),
                                                                                        len(streams),
                                                                                        len(subscriptions),
                                                                                        len(batchLogs))
                except:
                    msg = util.trace()
                self.response.out.write(msg)
            elif kind == 'sub':
                subscriptions = Subscription.all().fetch(limit)
                db.delete_async(subscriptions)
                hasNext = False
                if len(subscriptions) >= limit:
                    hasNext = True
                rst = {'is_ok':True, 'has_next':hasNext, 'count':limit}
                self.response.headers['Content-Type'] = 'application/json'
                self.response.out.write(simplejson.dumps(rst))


_handlers = [(r'/', MainHandler),
             (r'/init/(add|clear|new)$', InitHandler)]
application = webapp.WSGIApplication(_handlers)


def main():
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
